package main

import (
	"final-url/entity"
	"final-url/handlers"
	"final-url/middlewares"
	"final-url/pkg/final"
	"log"
	"net/http"
)

func main() {
	config, err := entity.NewConfigFromPath("config.json")
	if err != nil {
		log.Fatal(err)
	}

	if config.MT == nil || config.Alipay == nil {
		log.Fatal("config error: mt or alipay config is nil")
	}

	mtHttpClientPool := final.NewHttpPool(config.MT.ConcurrencyPerWorker * config.MT.WorkerNum)
	defer mtHttpClientPool.Close()
	mtWorkerPool := final.NewPool(final.NewWorkers(config.MT.WorkerNum, config.MT.ConcurrencyPerWorker, config.MT.ChanLength, mtHttpClientPool)...)
	defer mtWorkerPool.Close()
	config.MT.Pool = mtWorkerPool

	alipayHttpClientPool := final.NewHttpPool(config.Alipay.ConcurrencyPerWorker * config.Alipay.WorkerNum)
	defer alipayHttpClientPool.Close()
	alipayWorkerPool := final.NewPool(final.NewWorkers(config.Alipay.WorkerNum, config.Alipay.ConcurrencyPerWorker, config.Alipay.ChanLength, alipayHttpClientPool)...)
	defer alipayWorkerPool.Close()
	config.Alipay.Pool = alipayWorkerPool

	envMiddleware := middlewares.NewEnv(&config)
	ipMiddleware := middlewares.NewIp(&config)

	http.HandleFunc("/api/convert", envMiddleware(ipMiddleware(handlers.Convert)))

	log.Println("服务器启动在", config.Port)
	log.Fatal(http.ListenAndServe(config.Port, nil))
}
